const express = require('express')
const { Material } = require('../models')
const router = express.Router()

// 获取物料列表
router.get('/inventory', async (req, res) => {
  try {
    const { page = 1, limit = 10, category, type, search } = req.query
    
    const where = {}
    if (category) where.category = category
    if (type) where.type = type
    if (search) {
      where[Op.or] = [
        { name: { [Op.like]: `%${search}%` } },
        { code: { [Op.like]: `%${search}%` } }
      ]
    }
    
    const materials = await Material.findAndCountAll({
      where,
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit),
      offset: (page - 1) * limit
    })
    
    res.json({
      data: materials.rows,
      pagination: {
        total: materials.count,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    })
  } catch (error) {
    console.error('获取物料列表错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 创建物料
router.post('/inventory', async (req, res) => {
  try {
    const material = await Material.create(req.body)
    
    // 实时通知其他系统
    // io.to('all_systems').emit('material_created', material)
    
    res.json({ message: '物料创建成功', data: material })
  } catch (error) {
    console.error('创建物料错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 更新物料
router.put('/inventory/:id', async (req, res) => {
  try {
    const { id } = req.params
    const material = await Material.findByPk(id)
    
    if (!material) {
      return res.status(404).json({ message: '物料不存在' })
    }
    
    await material.update(req.body)
    
    // 实时通知更新
    // io.to('all_systems').emit('material_updated', material)
    
    res.json({ message: '物料更新成功', data: material })
  } catch (error) {
    console.error('更新物料错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 删除物料
router.delete('/inventory/:id', async (req, res) => {
  try {
    const { id } = req.params
    const material = await Material.findByPk(id)
    
    if (!material) {
      return res.status(404).json({ message: '物料不存在' })
    }
    
    await material.destroy()
    
    // 实时通知删除
    // io.to('all_systems').emit('material_deleted', { id })
    
    res.json({ message: '物料删除成功' })
  } catch (error) {
    console.error('删除物料错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 获取物料详情
router.get('/inventory/:id', async (req, res) => {
  try {
    const { id } = req.params
    const material = await Material.findByPk(id)
    
    if (!material) {
      return res.status(404).json({ message: '物料不存在' })
    }
    
    res.json({ data: material })
  } catch (error) {
    console.error('获取物料详情错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

// 库存预警
router.get('/inventory/warning', async (req, res) => {
  try {
    const materials = await Material.findAll({
      where: {
        currentStock: {
          [Op.lte]: sequelize.col('safeStock')
        }
      },
      order: [['currentStock', 'ASC']]
    })
    
    res.json({ data: materials })
  } catch (error) {
    console.error('获取库存预警错误:', error)
    res.status(500).json({ message: '服务器错误' })
  }
})

module.exports = router
